<?php
/**
 * @date        <!-- phpDesigner :: Timestamp [07-07-2010 23:01:04] -->
 * @filesource  class.stats.php
 * @package     WebCms
 * @copyright	Copyright (C) 2010
 * @author      Sérgio 'Horizak' Alves
 */

// Sem acesso directo
defined('_WEXEC') or die('Restricted access');

/**
 * Class estatisticas
 *
 */
class Stats {

  /**
   * Função construtora
   * 
   */
  function __construct() {
    $this->lastVisit = isset($_COOKIE['lastVisit']) ? $_COOKIE['lastVisit'] : null;
    $this->timeVisit = cms_date('time');

    $this->insertVisit();
  }

  /**
   * Insere a visita de x em x tempo
   * 
   */
  function insertVisit() {
    global $cms;

    $permited = cms_date('time','-12 hours');

    if ($permited >= $this->lastVisit or is_null($this->lastVisit)) {
      $ip = $cms->obj['user']->getData('checkIP');
      $country = $this->getCountry($ip);
      $client = $cms->obj['user']->getData('browser');
      $referer = cms_linkReferer();
      $page = $cms->global['server']['REQUEST_URI'];
      $created = cms_date('mysql');

      $sql = "INSERT INTO ".DBSTATS." (ip, country, client, referer, page, created)";
      $sql .= " VALUES ('{$ip}','{$country}','{$client}','{$referer}','{$page}','{$created}')";
      $cms->obj['mysql']->sql($sql);

      cms_cookie('lastVisit',$this->timeVisit);
    }

    $this->insertReferer();
  }

  /**
   * Pega o pais
   * 
   * @var           string $ip - ip para retornar o pais
   * @return        string pais
   */
  function getCountry($ip) {
    global $cms;

    $sql = "SELECT country FROM ".DBIP2N;
    $sql .= " WHERE ip < INET_ATON('{$ip}')";
    $sql .= " ORDER BY ip DESC LIMIT 0,1";
    $cms->obj['mysql']->sql($sql);
    $row = mysql_fetch_array($cms->obj['mysql']->result);

    return $row['country'];
  }

  /**
   * Insere o refer
   * 
   */
  function insertReferer() {
    global $cms;

    $referer = cms_linkReferer();

    if ($referer != false) {
      $array = explode('/',$referer);
      $referer = str_replace('www.','',$array[2]);

      $sql = "SELECT clicks FROM ".DBSTATSREF;
      $sql .= " WHERE referer = '{$referer}'";

      if ($cms->obj['mysql']->getTotal($sql)) {
        $row = mysql_fetch_array($cms->obj['mysql']->result);
        $clicks = $row['clicks'] + 1;

        $sql = "UPDATE ".DBSTATSREF;
        $sql .= " SET clicks = '{$clicks}'";
        $sql .= " WHERE referer = '{$referer}'";
        $cms->obj['mysql']->sql($sql);
      } else {
        if ($referer != $cms->global['server']['SERVER_NAME']) {
          $sql = "INSERT INTO ".DBSTATSREF;
          $sql .= " (referer, clicks)";
          $sql .= " VALUES ('{$referer}', '1')";
          $cms->obj['mysql']->sql($sql);
        }
      }
    }
  }

  /**
   * Pega o total de visitas num periodo
   * 
   */
  function totalFilter($date = null,$format = '%Y-%m-%d') {
    global $cms;

    $sql = "SELECT COUNT(*) AS count FROM ".DBSTATS;

    if ($date) $sql .= " WHERE DATE_FORMAT(created,'$format') = '{$date}'";

    $cms->obj['mysql']->sql($sql);
    $row = mysql_fetch_array($cms->obj['mysql']->result);

    return $row['count'];
  }

  /**
   * Pega o total de visitas
   * 
   */
  function totalVisits() {
    return $this->totalFilter();
  }

  /**
   * Pega as visitas do dia
   * 
   */
  function totalDay() {
    return $this->totalFilter(cms_date('Y-m-d'));
  }

  /**
   * Pega as visitas de ontem
   * 
   */
  function totalYesterday() {
    return $this->totalFilter(cms_date('Y-m-d',cms_date('time','-1 day')));
  }

  /**
   * Pega as visitas do mês
   * 
   */
  function totalMonth() {
    return $this->totalFilter(cms_date('Y-m'),'%Y-%m');
  }

  /**
   * Pega o total de utilizadores registados
   * 
   */
  function totalUsers($tbl = DBUSER,$enabled = 'enabled') {
    global $cms;

    $sql = "SELECT COUNT(*) AS count FROM {$tbl}";
    $sql .= " WHERE {$enabled} = '1'";
    $cms->obj['mysql']->sql($sql);
    $row = mysql_fetch_array($cms->obj['mysql']->result);

    return $row['count'];
  }
}
?>